package com.mingrisoft;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;


public class dataWatchActivity extends Activity implements View.OnClickListener{
    private String mqtt_sub_topic = "controlDevice";          //需要订阅的主题
    private String mqtt_pub_topic = "controlDevice";          //需要发布的主题
    private int Qos = 1;
    private mqttManager mqtt_manager;
    private EditText cycleEdit;
    private Button cycBtn;
    private Timer timer;
    private Handler handler=new Handler();
    private TextView tv1,tv2,tv3,tv4,tv5,tv6;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_watch);
        tv1=(TextView)findViewById(R.id.tvTempVal);
        tv2=(TextView)findViewById(R.id.tvHumVal);
        tv3=(TextView)findViewById(R.id.tvAHumVal);
        tv4=(TextView)findViewById(R.id.tvCo2Val);
        tv5=(TextView)findViewById(R.id.tvLightVal);
        tv6=(TextView)findViewById(R.id.datafromDev);
        cycBtn=(Button)findViewById(R.id.cycleBtn);
        cycleEdit=(EditText)findViewById(R.id.cycleEdit);
        TextView [] tvs={tv1,tv2,tv3,tv4,tv5,tv6};
        mqtt_manager=mqttManager.getInstance(tvs,6);
        mqtt_manager.flashAbtrr(tvs, 6);
        mqtt_manager.subscribeMessage(mqtt_sub_topic, Qos);
        mqtt_manager.mqqtBack();
        startTimer();
       cycBtn.setOnClickListener(this);

    }
    private void startTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 在UI线程中更新TextView的文本内容为空字符串
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        tv6.setText(""); // 清空TextView的文本内容
                    }
                });
            }
        }, 0, 60000); // 每隔30秒清理一次
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 在Activity销毁时停止定时器
        stopTimer();
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel(); // 取消定时器任务
            timer.purge(); // 清除定时器队列
        }
    }
    public void onClick(View view){
        if(view.getId()==R.id.cycleBtn){
            String interval=cycleEdit.getText().toString();
            int count =0;
            count+=1;
            String msg="{"+"\"seq\":"+count+",\"type\":1"+",\"Interval\":"+interval+"}";
            mqtt_manager.publishMessage(mqtt_pub_topic,msg);
            Toast.makeText(dataWatchActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    }
}
